<template>
  <div class="right-menu" v-show="visible" :style="{ top: y + 'px', left: x + 'px' }">
    <div class="menu-item" v-for="item in menuList" @click="handleAction(item.action)">
      <i :class="item.icon"></i>
      <span>{{ item.name }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

const menuList = [
  {
    name: '编辑',
    icon: 'ri-edit-line',
    action: 'edit'
  },
  {
    name: '删除',
    icon: 'ri-delete-bin-line',
    action: 'delete'
  },
  {
    name: '置顶',
    icon: 'ri-check-line',
    action: 'complete'
  },
  {
    name: '复制',
    icon: 'ri-file-copy-line',
    action: 'copy'
  }
]

// 菜单显示状态
const visible = ref(false)
// 菜单位置
const x = ref(0)
const y = ref(0)

// 定义事件
const emit = defineEmits(['action'])

// 处理菜单项点击
const handleAction = (action: string) => {
  emit('action', action)
  hideMenu()
}

// 显示菜单
const showMenu = (event: MouseEvent) => {
  event.preventDefault()
  x.value = event.clientX
  y.value = event.clientY
  visible.value = true

  // 确保菜单不超出窗口边界
  nextTick(() => {
    const menu = document.querySelector('.right-menu') as HTMLElement
    if (!menu) return

    const menuRect = menu.getBoundingClientRect()
    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    if (menuRect.right > windowWidth) {
      x.value = windowWidth - menuRect.width
    }

    if (menuRect.bottom > windowHeight) {
      y.value = windowHeight - menuRect.height
    }
  })
}

// 隐藏菜单
const hideMenu = () => {
  visible.value = false
}

// 点击其他区域隐藏菜单
const handleClickOutside = (event: MouseEvent) => {
  const menu = document.querySelector('.right-menu')
  if (menu && !menu.contains(event.target as Node)) {
    hideMenu()
  }
}

// 导出方法供父组件调用
defineExpose({
  showMenu,
  hideMenu
})

// 生命周期钩子
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  // 添加ESC键关闭菜单
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') hideMenu()
  })
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  document.removeEventListener('keydown', (e) => {
    if (e.key === 'Escape') hideMenu()
  })
})
</script>

<style scoped lang="scss">
.right-menu {
  position: fixed;
  background: var(--xz-card-bg);
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  min-width: 120px;
  z-index: 1000;
  overflow: hidden;
  padding: 4px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-item {
  padding: 4px 8px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  border-radius: 4px;
}

.menu-item:hover {
  background-color: var(--xz-theme);

  i {
    transition: all 0.3s ease-in-out;
    color: var(--xz-white);
  }

  span {
    transition: all 0.3s ease-in-out;
    color: var(--xz-white);
  }
}

.menu-item i {
  margin-right: 8px;
  font-size: 16px;
}

.menu-item span {
  font-size: 14px;
}
</style>
